import React from 'react'
import { addTesk } from '../../../store/Slice/taskReducer'
import { useDispatch,useSelector} from 'react-redux'
import { nanoid } from 'nanoid'
export default function Header() {
const dispatch  = useDispatch()


const addTeskHandle=(e)=>{
    if (e.keyCode!==13)return
    const todoList={id:nanoid(),todo:e.target.value,check:false}
    dispatch(addTesk(todoList))
    e.target.value = ''
}

//初始化是异步  拿到newList直接设置 当前newList是数组,会在初始化前把localStorage变成空数组,设置定时器后,将设置localStorage变成异步,会在初始化后执行,初始化设置store值,重新执行代码,拿到最新newList,再设置localStorage
const newList = useSelector(state => state.tesk.tesk)
function setLocastorge(newList){
    setTimeout(() => {
        localStorage.setItem("todoList", JSON.stringify(newList))
    }, 1000);
}
setLocastorge(newList)


    return (
        <div>
            <div className="todo-header">
                <input onKeyUp={addTeskHandle} type="text" placeholder="请输入你的任务名称，按回车键确认" />
            </div>
        </div>
    )
}
